let that
class Tab {
    constructor(id) {
        that = this
        this.main = document.querySelector(id)
        this.addBtn = this.main.querySelector('.tabadd')
        this.ul = this.main.querySelectorAll('.firstNav ul')
        this.sectionsFather = this.main.querySelector('.tabscon')
    }
    // 动态获取
    updata() {
        // 获取li
        this.lis = this.main.querySelectorAll('.firstNav li')
        // 获取选项卡
        this.sections = this.main.querySelectorAll('.tabscon section')
        // 获取删除按钮
        this.delBtns = this.main.querySelectorAll('.firstNav li .iconfont')
        // 获取span标签
        this.spans = this.main,querySelectorAll('.firstNav li span:first-child')
    }
    // 初始化绑定事件
    init() {
        this.addBtn.addEventListener('click', this.addTabs)
        this.updata()
        // 绑定点击事件
        this.lis.forEach((item, index) => {
            item.index = index
            item.addEventListener('click', this.toggleTabs)
            // console.log(1)
        })
        // 绑定删除事件
        this.delBtns.forEach(item => {
            item.addEventListener('click', this.delTabs)
        })
        // 绑定双击编辑事件
        this.spans.forEach(item =>{
            item.addEventListener('dbclick',this.editTabs)
        })
    }
    // 排他事件
    clearClassName() {
        this.lis.forEach(item => {
            item.className = ''
        })
        this.sections.forEach(item => {
            item.className = ''
        })
    }
    // 切换事件
    toggleTabs() {
        // console.log(this.index)
        that.clearClassName()
        this.className = 'liactive'
        that.sections[this.index].className = 'conactive'
    }
    // 添加事件
    addTabs() {
        that.clearClassName()
        const li = `<li class="liactive"><span>新增测试</span><span  class="iconfont icon-guanbi"></span></li>`
        const section = `<section class="conactive">测试${Math.random()}<  section>`
        that.ul.insertAdjacentHTML('beforeend', li)
        that.sectionsFather.insertAdjacentHTML('beforeend', section)
        that.init()
    }
    // 删除事件
    delTabs(e) {
        e.stopPropagation()
        let index = this.parentNode.index
        this.parentNode.remove()
        this.sections[index].remove()
        that.init()
        if (document.querySelector('.liactive')) return;
        // index--;
        // that.lis[index]&&that.lis[index].click();
        // index ? that.lis[index - 1]?.click : that.lis[index]?clock()
        if (index) {
            if (that.lis[index - 1]) {
                that.lis[index - 1].click()
            }
        } else {
            if (that.lis[index]) {
                that.lis[index].click()
            }
        }
    }
    // 绑定编辑事件
    editTabs(){
        window.getSelection ? window.getSelection().removeAllRanges() : document.section.empty()
        let str = this.innerHTML
        this.innerHTML = `<input type = "text">`
        let input = this.children[0]
        input.value = str
    }
}
new Tab('#tab')